/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hxg.portmgr.core.ip;

import hxg.portmgr.core.device.Device;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author hxg
 */
public class IpSubnetNode implements Comparable<IpSubnetNode> {

    IpSubnetNode upNode; //上级IpSubnet
    final IpSubnet ipSubnet;
    final Collection<Device> devs = new HashSet<Device>();
    private final static ConcurrentHashMap<IpSubnet, IpSubnetNode> nodeMap = new ConcurrentHashMap<IpSubnet, IpSubnetNode>();

    private IpSubnetNode(IpSubnet ipsubnet) {
        this.ipSubnet = ipsubnet;
        if (ipsubnet.mask >= 1) {
            upNode = getIpSubnetNode(ipSubnet.getUpSubnet());
        }
        //upIpSubnet=ipsubnet.getUpSubnet();
    }
    //<editor-fold defaultstate="collapsed" desc="Setter and Getter"> 

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 19 * hash + (this.ipSubnet != null ? this.ipSubnet.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final IpSubnetNode other = (IpSubnetNode) obj;
        if (this.ipSubnet != other.ipSubnet && (this.ipSubnet == null || !this.ipSubnet.equals(other.ipSubnet))) {
            return false;
        }
        return true;
    }

    
    
    public Collection<Device> getDevices() {
        return Collections.unmodifiableCollection(devs);
    }

    public void addDevices(Device dev) {
        devs.add(dev);
    }

    public void addAllDevice(Collection<Device> devs) {
        this.devs.addAll(devs);
    }

    public void removeDevice(Device dev) {
        devs.remove(dev);
    }

    public void clearDevice() {
        devs.clear();
    }

    public IpSubnet getIpSubnet() {
        return ipSubnet;
    }

    public IpSubnetNode getUpNode() {
        return upNode;
    }

    public void setUpNode(IpSubnetNode upNode) {
        this.upNode = upNode;
    }
    //</editor-fold>

    public static IpSubnetNode getIpSubnetNode(IpSubnet ipSubnet) {
        if (!nodeMap.containsKey(ipSubnet)) {
            IpSubnetNode node = new IpSubnetNode(ipSubnet);
            nodeMap.put(ipSubnet, node);
        }
        return nodeMap.get(ipSubnet);
    }

    public static Collection<IpSubnetNode> getKnownIpSubnetNodes() {
        return nodeMap.values();
    }

    @Override
    public String toString() {
        return ipSubnet.toString() + "[" + devs.size() + "]";
    }

    @Override
    public int compareTo(IpSubnetNode o) {
        return this.ipSubnet.hashCode()-o.ipSubnet.hashCode();
    }
}
